package com.qifei.xmlg_backend.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.qifei.xmlg_backend.entity.Result;
import com.qifei.xmlg_backend.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 在协议头中获取token
        String authHeader = request.getHeader("token");

        // 如果上面没有成功获取到 就从参数里面获取  ai要从param中获取
        if (!StringUtils.hasText(authHeader)) {
            authHeader = request.getParameter("token");
        }

        // 如果没有成功获取到 就返回未登录
        if (!StringUtils.hasText(authHeader)){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return notLogin(response);
        }

        String token = authHeader;

        try {
            // 用jwt工具解析token里面的数据
            Claims claims = JwtUtils.parseJWT(token);
            String username = (String) claims.get("username");
            log.info(username);
            request.setAttribute("username", username);

            return true;
        }catch (Exception e){
            // 解析错误的话表示这个token
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return notLogin(response);
        }
    }

    /**
     * 返回未登录响应并终止后续流程
     */
    private boolean notLogin(HttpServletResponse response) throws Exception {
        Result res = Result.error("NOT_LOGIN");
        String json = JSONObject.toJSONString(res);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
        return false;
    }
}
